#!/usr/bin/env python
# -*- coding: UTF-8; indent-tabs-mode:nil; tab-width:4 -*-

# This file is part of DITA DTD Generator.
#
# DITA DTD Generator is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DITA DTD Generator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DITA DTD Generator.  If not, see <http://www.gnu.org/licenses/>.

"""Command line interface to DITA DTD Generator."""

import sys
import ditagen.dita
import ditagen.dtdgen
from ditagen.dita.v1_2 import *
from ditagen.dita.v1_1 import *
import ditagen.generator
from optparse import OptionParser

OUTPUT_MAP = {
    "specialization": ditagen.dita.SpecializationType,
    "shell": ditagen.dita.ShellType
    }
DOMAIN_MAP = {
    "1.1": {
        "ui": ditagen.dita.v1_1.UiDomain,
        "hi": ditagen.dita.v1_1.HiDomain,
        "pr": ditagen.dita.v1_1.PrDomain,
        "sw": ditagen.dita.v1_1.SwDomain,
        "ut": ditagen.dita.v1_1.UtDomain,
        "indexing": ditagen.dita.v1_1.IndexingDomain,
        "mapgroup": ditagen.dita.v1_1.MapGroupDomain,
        "abbreviated": ditagen.dita.v1_1.AbbreviatedFormDomain,
        "xnal": ditagen.dita.v1_1.XNALDomain,
        },
    "1.2": {
        "ui": ditagen.dita.v1_2.UiDomain,
        "hi": ditagen.dita.v1_2.HiDomain,
        "pr": ditagen.dita.v1_2.PrDomain,
        "sw": ditagen.dita.v1_2.SwDomain,
        "ut": ditagen.dita.v1_2.UtDomain,
        "indexing": ditagen.dita.v1_2.IndexingDomain,
        "learning": ditagen.dita.v1_2.LearningDomain,
        "learningmeta": ditagen.dita.v1_2.LearningMetaDomain,
        "learningmap": ditagen.dita.v1_2.LearningMapDomain,
        #"mitask": ditagen.dita.v1_2.MachineIndustryTaskDomain,
        "taskreq": ditagen.dita.v1_2.TaskRequirementsDomain,
        "hazardstatement": ditagen.dita.v1_2.HazardStatementDomain,
        "mapgroup": ditagen.dita.v1_2.MapGroupDomain,
        "abbreviated": ditagen.dita.v1_2.AbbreviatedFormDomain,
        "xnal": ditagen.dita.v1_2.XNALDomain,
        "delay": ditagen.dita.v1_2.UserDelayedResolutionDomain,
        "classify": ditagen.dita.v1_2.ClassifyDomain,
        #"taskbody": ditagen.dita.v1_2.MachineIndustryTaskbodyConstraints,
        "taskbody": ditagen.dita.v1_2.MachineryTaskbodyConstraints,
        "strictTaskbody": ditagen.dita.v1_2.StrictTaskbodyConstraints
        }
    }
TOPIC_MAP = {
    "1.1": {
        "concept": ditagen.dita.v1_1.ConceptType,
        "reference": ditagen.dita.v1_1.ReferenceType,
        "task": ditagen.dita.v1_1.TaskType,
        "topic": ditagen.dita.v1_1.TopicType,
        "map": ditagen.dita.v1_1.MapType,
        "bookmap": ditagen.dita.v1_1.BookMapType,
        },
    "1.2": {
        "concept": ditagen.dita.v1_2.ConceptType,
        "reference": ditagen.dita.v1_2.ReferenceType,
        "task": ditagen.dita.v1_2.TaskType,
        "generalTask": ditagen.dita.v1_2.GeneralTaskType,
        "topic": ditagen.dita.v1_2.TopicType,
        "machineTask": ditagen.dita.v1_2.MachineryTaskType,
        "map": ditagen.dita.v1_2.MapType,
        "bookmap": ditagen.dita.v1_2.BookMapType,
        "classifyMap": ditagen.dita.v1_2.ClassificationMapType,
        "subjectScheme": ditagen.dita.v1_2.SubjectSchemeMapType,
        "learningAssessment": ditagen.dita.v1_2.LearningAssessmentType,
        "learningBookmap": ditagen.dita.v1_2.LearningBookMapType,
        "learningContent": ditagen.dita.v1_2.LearningContentType,
        "learningMap": ditagen.dita.v1_2.LearningMapType,
        "learningOverview": ditagen.dita.v1_2.LearningOverviewType,
        "learningPlan": ditagen.dita.v1_2.LearningPlanType,
        "learningSummary": ditagen.dita.v1_2.LearningSummaryType
        }
    }

def main():
    """Main method."""
    __type = None
    #__root = None
    #__owner = None
    #__nested = None
    __remove = {}
    __global_atts = None
    #__format = None
    __domains = []
    #__types = []
    #__version = 1.1
    #__plugin_name = None
    #__stylesheet = None
    
    #__dms = []    
    
    # new arguments
    __parser = OptionParser(usage="usage: %prog [options] type topic [root] [title]",
                            description="DITA Generator.")
    __parser.add_option("-d", "--domain", action="append", dest="domains",
                        help="Add domain DOMAIN", metavar="DOMAIN")
    __parser.add_option("-v", "--version", dest="version", choices=("1.1", "1.2"),
                        help="DITA version. Defaults to 1.1.", metavar="VERSION")
    __parser.add_option("-o", "--owner", dest="owner",
                        help="Owner in FPI.", metavar="OWNER")
    __parser.add_option("-f", "--format", dest="format", choices=("dtd", "mod", "ent", "zip", "plugin"),
                        help="Output format, one of dtd, mod, ent, zip, plugin. Defaults to plugin.", metavar="FORMAT")
    __parser.add_option("-s", "--stylesheet", dest="stylesheet",
                        help="Stylesheet stump base.", metavar="STYLE")
    __parser.add_option("-p", "--plugin-name", dest="plugin_name",
                        help="Plugin name. Defaults to root name.", metavar="PLUGIN")
    __parser.add_option("-n", "--nested", dest="nested", action="store_true",
                        help="Support nested topics.")
    #__parser.add_option("-r", "--root", dest="root",
    #                    help="Root name.", metavar="ROOT")
    #__parser.add_option("-t", "--title", dest="title",
    #                    help="Title.", metavar="TITLE")
    __parser.set_defaults(version="1.1")
    __parser.set_defaults(nested=False)
    __parser.set_defaults(format="plugin")
    (options, args) = __parser.parse_args()
    # read arguments
    if len(args) >= 1:
        if args[0] in OUTPUT_MAP:
            __output_type = OUTPUT_MAP[args[0]]
        else:
            __parser.error("output type %s not found, supported types: %s."
                           % (args[0], ", ".join(OUTPUT_MAP.keys())))
    else:
        __parser.error("output type not set")

    if len(args) >= 2:
        if args[1] in TOPIC_MAP[options.version]:
            __type = TOPIC_MAP[options.version][args[1]]()
        else:
            __parser.error("topic type %s not found, supported topics: %s."
                           % (args[1], ", ".join(TOPIC_MAP[options.version].keys())))
    else:
        __parser.error("topic not set")
    if len(args) >= 3:
        options.root = args[2]
    if len(args) >= 4:
        options.title = args[3]
    if options.domains != None:
        for __d in options.domains:
            if __d in DOMAIN_MAP[options.version]:
                __domains.append(DOMAIN_MAP[options.version][__d]())
            else:
                __parser.error("domain %s not found, supported domains: %s."
                               % (__d, ", ".join(DOMAIN_MAP[options.version].keys())))
    
    if  hasattr(options, "root") and options.root is not None:
        if hasattr(options, "title") and options.title:
            __t = options.title
        else:
            __t = options.root.capitalize()
        #__type = ditagen.dita.SpecializationType(options.root, __t, __type,
        __type = __output_type(options.root, __t, __type,
                               options.owner, options.root)
    elif options.format in ("mod", "ent", "zip"):
        __parser.error("cannot generate %s for base topic type." % options.format)

    # run generator
    if options.format == u"plugin":
        __dita_gen = ditagen.generator.PluginGenerator()
        __dita_gen.set_output(sys.stdout)
        __dita_gen.set_topic_type(__type)
        __dita_gen.set_domains(__domains)
        #__dita_gen.set_root(__root)
        #__dita_gen.set_owner(__owner)
        __dita_gen.set_nested(options.nested)
        __dita_gen.set_version(options.version)
        if hasattr(options, "title") and  options.title:
            __dita_gen.set_title(options.title)
        if options.stylesheet:
            __dita_gen.set_stylesheet(options.stylesheet)
        __dita_gen.set_plugin_name(options.plugin_name)
        
        #__file_name = __dita_gen.get_file_name(__type, options.root, "zip")
        __dita_gen.generate_plugin()
    else:
        __dita_gen = ditagen.generator.DitaGenerator()
        __dita_gen.set_output(sys.stdout)
        __dita_gen.set_topic_type(__type)
        __dita_gen.set_domains(__domains)
        #__dita_gen.set_root(__root)
        #__dita_gen.set_owner(__owner)
        __dita_gen.set_nested(options.nested)
        __dita_gen.set_version(options.version)
        if hasattr(options, "title") and  options.title:
            __dita_gen.set_title(options.title)
        
        if options.format == u"dtd":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_dtd()
        elif options.format == u"mod":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_mod()
        elif options.format == u"ent":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_ent()
        elif options.format == u"zip":
            #__file_name = __dita_gen.get_file_name(__type, __root, "zip")
            __dita_gen.generate_zip(sys.stdout)
        #elif __format == u"tgz":
        #    __file_name = __dita_gen.get_file_name(__type, __root, "tar.gz")
        #    __dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested, __remove, __global_atts)
        #elif __format == u"xzip":
        #    __file_name = __dita_gen.get_file_name(__type, __root, "zip")
        #    zip_dita_gen = ditagen.generator.ZipGenerator(sys.stdout)
        #    zip_dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested)

if __name__ == "__main__":
    main()
